import colors from "picocolors";
import fs from "fs-extra";
import fetch from "node-fetch";
import path from "path";
import packageLock from "../package-lock.json";

async function downloadTgzFiles() {
  console.log(colors.green("Downloading tgz files..."));
  const rootDir = process.cwd();

  const length = Object.keys(packageLock.packages).length;
  let count = 0;

  for (const key in packageLock.packages) {
    count++;

    if (Object.prototype.hasOwnProperty.call(packageLock.packages, key)) {
      const module = packageLock.packages[key];
      if (module.resolved && module.resolved.endsWith(".tgz")) {
        const url = module.resolved;
        const fileName = path.basename(new URL(url).pathname);
        const filePath = path.join(rootDir, "tgzs/18", key, fileName);

        if (fs.existsSync(filePath)) {
          console.log(`${count}/${length} ${colors.gray(key + "/" + fileName)}`);
          continue;
        }

        await waiting(1000);
        const response = await fetch(url);
        if (response.ok) {
          const blob = await response.blob();
          const buffer = await blob.arrayBuffer();
          const data = new DataView(buffer);
          fs.outputFileSync(filePath, data);
          console.log(`${count}/${length} ${key}/${fileName}`);
        } else {
          console.error(`${count}/${length} Failed to download ${url}`);
        }
      }
    }
  }

  console.log(colors.green("All tgz files downloaded successfully."));
}

function waiting(ms: number) {
  return new Promise((resolve) => setTimeout(resolve, Math.random() * 0.3 * ms + ms * 0.7));
}

downloadTgzFiles();
